package service

import (
	"encoding/json"
	"errors"
	"os"
	"sort"
	"time"
	"your-tool/internal/define"

	"github.com/google/uuid"
)

func TimeLineList() ([]*define.TimeLine, error) {
	dir, _ := os.Getwd()
	b, err := os.ReadFile(dir + string(os.PathSeparator) + define.ConfigName)
	if errors.Is(err, os.ErrNotExist) {
		// return nil, err
		return nil, nil
	}
	tl := new(define.TimeLineList)
	err = json.Unmarshal(b, tl)
	if err != nil {
		return nil, err
	}
	sort.SliceStable(tl.List, func(i, j int) bool {
		return tl.List[i].TimeString > tl.List[j].TimeString
	})
	return tl.List, nil
}

func TimeLineCreate(timeLine *define.TimeLine) error {

	if timeLine.Content == "" {
		return errors.New("事件内容不能为空")
	}
	if timeLine.TimeString == "" {
		return errors.New("事件时间不能为空")
	}
	if timeLine.Name == "" {
		return errors.New("事件主题不能为空")
	}
	timeLine.Identify = uuid.New().String()
	timeLine.CreateTime = time.Now().Format("2006-01-02 15:04:05")
	timeLine.UpdateTime = time.Now().Format("2006-01-02 15:04:05")

	data := new(define.TimeLineList)
	dir, _ := os.Getwd()
	b, err := os.ReadFile(dir + string(os.PathSeparator) + define.ConfigName)
	// 不存在则创建
	if errors.Is(err, os.ErrNotExist) {
		// 数据
		data.List = []*define.TimeLine{timeLine}
		b, _ := json.Marshal(data)
		// 创建
		os.MkdirAll(dir, os.ModePerm)
		os.WriteFile(dir+string(os.PathSeparator)+define.ConfigName, b, os.ModePerm)
		return nil
	}
	json.Unmarshal(b, data)
	data.List = append(data.List, timeLine)
	b, _ = json.Marshal(data)
	os.WriteFile(dir+string(os.PathSeparator)+define.ConfigName, b, os.ModePerm)
	return nil
}

func TimeLineEdit(timeLine *define.TimeLine) error {
	if timeLine.Identify == "" {
		return errors.New("identify不能为空")
	}

	if timeLine.Content == "" {
		return errors.New("事件内容不能为空")
	}
	if timeLine.TimeString == "" {
		return errors.New("事件时间不能为空")
	}
	if timeLine.Name == "" {
		return errors.New("事件主题不能为空")
	}

	data := new(define.TimeLineList)
	dir, _ := os.Getwd()
	b, err := os.ReadFile(dir + string(os.PathSeparator) + define.ConfigName)
	// 不存在则报错
	if err != nil {
		return err
	}
	json.Unmarshal(b, data)
	for i, v := range data.List {
		if v.Identify == timeLine.Identify {
			data.List[i] = timeLine
			break
		}
	}
	b, _ = json.Marshal(data)
	os.WriteFile(dir+string(os.PathSeparator)+define.ConfigName, b, os.ModePerm)
	return nil
}

func TimeLineItem(identify string) (*define.TimeLine, error) {
	data := new(define.TimeLineList)
	dir, _ := os.Getwd()
	b, err := os.ReadFile(dir + string(os.PathSeparator) + define.ConfigName)
	if errors.Is(err, os.ErrNotExist) {
		return nil, err
	}
	json.Unmarshal(b, data)
	for _, v := range data.List {
		if v.Identify == identify {
			return v, nil
		}
	}
	return nil, errors.New("not found")
}